package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;



import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    static final String prefixPh = "CHECK_CODE";//手机前缀

    @Autowired
    private SmsTemplate template;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mqMessageServicel;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证码
     * @param phone
     */
    public void sendMsg(String phone) {
        //根据手机号查询用户,如果用户存在,判断是否被冻结
        User user = userApi.findByMobile(phone);
        if (user != null){
            userFreezeService.checkUserStatus("1",user.getId());
        }
        //1.随机生成6位数字验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2.调用SmsTemplate发送验证码到手机上
        //template.sendSms(phone,code);
        //3.将验证码存入Redis设置5分钟失效
        redisTemplate.opsForValue().set(prefixPh+phone,code,Duration.ofMinutes(5));
    }

    /**
     *手机登录验证注册
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        String type = "0101";
        //1.从redis中获得验证码
        String redisCode = redisTemplate.opsForValue().get(prefixPh + phone);
        //2.对验证码进行校验
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
           //验证码无效
           throw new BusinessException(ErrorResult.loginError());
        }
        //3.删除redis中的验证码
        redisTemplate.delete(prefixPh+phone);
        //4.通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        //5.如果用户不存在，创建用户保存到数据库中
        boolean isNew = false;
        if (user == null){
            type = "0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, "123456");
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
            userApi.update(user);
        }
        mqMessageServicel.sendLogService(user.getId(),type,"user",null);
        //6.通过JWT生成token(将id和手机号码存入)
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7.构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);//手机和ID
        retMap.put("isNew",isNew);
        return retMap;
    }
}
